package y2017.date0216am.对象流;

import java.io.*;

public class ObjectIO {
    public static void saveObject(Object obj, String filePath) {
        File file = new File(filePath);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(obj);
            oos.flush();
            oos.close();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> T readObject(String filePath) {
        File file = new File(filePath);
        Object obj = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            ObjectInputStream ois = new ObjectInputStream(fis);
            obj = ois.readObject();
            ois.close();
            fis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return (T) obj;
    }

    @SuppressWarnings("unchecked")
    public static <T> T cloneObject(Object obj) {
        Object objClone = null;
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(obj);//将对象通过对象输出流，缓存到数组输出流中

            oos.flush();
            byte[] objTemp = baos.toByteArray();//对象缓存为数组了

            //开始克隆
            ByteArrayInputStream bais = new ByteArrayInputStream(objTemp);
            ObjectInputStream ois = new ObjectInputStream(bais);
            objClone = ois.readObject();

            ois.close();
            bais.close();
            oos.close();
            baos.close();


        } catch (Exception e) {
            e.printStackTrace();
        }
        return (T) objClone;
    }
}
